import axios from 'axios'
// import { useRouter } from 'vue-router';
// import { BASE_URL } from './config';

import { removeToken, getToken } from '@/utils/cookies'
import { ElLoading, ElMessage } from 'element-plus'
import { TIMEOUT, BASE_URL } from './config'
import 'element-plus/theme-chalk/el-loading.css'
import 'element-plus/theme-chalk/el-message.css'
import router from '@/router'
// import { storeToRefs } from 'pinia';
// import useMainState from '../../stores/modules/mainState';
// const mainState = useMainState();
// const { token } = storeToRefs(mainState);
// const router = useRouter();
const axiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})
let loading = undefined
// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // Add X-Access-Token header to every request, you can add other custom headers here

    if (getToken() && config.headers) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    // debugger;
    if (config.isShowLoading === 'yes') {
      loading = ElLoading.service({
        lock: true,
        text: '正在加载中...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
    }

    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

axiosInstance.interceptors.response.use(
  (response) => {
    setTimeout(() => {
      loading?.close()
    }, 500)

    const res = response.data ?? response
    if (res.code) {
      if (Number(res.code) !== 200 && res.code !== 203) {
        if (res.code === 401) {
          removeToken()
          router.replace('/login')
          return Promise.reject({
            hideErr: true
          })
        }
        return Promise.reject(new Error(res.msg || 'Error'))
      } else {
        return res
      }
    } else {
      return res
    }
  },
  (error) => {
    setTimeout(() => {
      loading?.close()
    }, 500)
    let err = {}

    if (error.response) {
      const { data = {} } = error.response
      err = {
        message: data.message || '请求异常',
        type: 'error'
      }
    } else if (error.message && error.message.includes('timeout')) {
      err = {
        message: '请求超时，请检查网络连接!',
        type: 'error'
      }
    }
    return Promise.reject(err)
  }
)

export function formateURLOnlyGet(link, params) {
  let url = link
  const data = Object.entries(params)

  if (data.length) {
    url += url.indexOf('?') == -1 ? '?' : ''
    url += Object.entries(data)
      .map((item) => {
        return item[1].join('=')
      })
      .join('&')
  }
  return url
}

export function errorHandler(reqPromise, option) {
  return reqPromise.catch((err) => {
    if (!err.hideErr) {
      console.log('这里执行了1')
      ElMessage({
        message: err.message || '请求异常',
        type: err.type || 'error',
        duration: 3 * 1000
      })
    }
    return Promise.reject(err)
  })
}

const defaultOption = {
  showError: true,
  config: {
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    }
  }
}
/**
 * GET请求方法
 * @param {String} url 请求地址
 * @param {json} params 请求参数
 */
export function getData(url, params, options = defaultOption) {
  return errorHandler(axiosInstance.get(url, { params: { ...params } }), options)
}
export function putData(url, params, options = defaultOption) {
  const config = options.config
  const data =
    config.headers && config.headers['Content-Type'] === 'multipart/form-data'
      ? params
      : JSON.stringify(params)

  return errorHandler(axiosInstance.put(url, data, config), options)
}
export function postData(url, params, options = defaultOption) {
  const config = options.config
  const data =
    config.headers && config.headers['Content-Type'] === 'multipart/form-data'
      ? params
      : JSON.stringify(params)

  return errorHandler(axiosInstance.post(url, data, config), options)
}
export function deleteData(url, params, options = defaultOption) {
  return errorHandler(axiosInstance.delete(url, { params }), options)
}
